package myJs.implicits

import myJs.myPkg.rSelect.SelectOption
import myJs.myPkg.reactHookForm.ErrorField

import scala.scalajs.js
import scala.scalajs.js.{JSON, |}
import myJs.Implicits._

/**
 * Created by Administrator on 2020/1/16
 */
trait MyErrorFieldTool {

  implicit class MyErrorField(v: js.Dictionary[ErrorField]) {

    def deepGet(name: String) = {
      val names = name.split("\\.").toList

      def loop(names: List[String], v: js.Dictionary[ErrorField]): ErrorField = {
        names match {
          case x :: Nil =>
            v(x)
          case x :: xs =>
            if (xs.head.isInt) {
              val curI = xs.head.toInt
              val array = v(x).asInstanceOf[js.Array[js.Dictionary[ErrorField]]]
              val curV = array(curI)
              loop(names.drop(2), curV)
            } else {
              val curV = v(x).asInstanceOf[js.Dictionary[ErrorField]]
              loop(xs, curV)
            }

        }
      }

      loop(names, v)
    }


    def deepDefinedAt(name: String) = {
      val names = name.split("\\.").toList

      def loop(names: List[String], vOp: Option[js.Dictionary[ErrorField]]): Boolean = {
        names match {
          case x :: Nil =>
            vOp.flatMap { v =>
              v.get(x)
            }.isDefined
          case x :: xs =>
            if (xs.head.isInt) {
              val curI = xs.head.toInt
              val curV = vOp.flatMap { v =>
                v.get(x)
              }.flatMap { y =>
                val array = y.asInstanceOf[js.Array[js.UndefOr[js.Dictionary[ErrorField]]]]
                array.toList.get(curI)
              }.flatMap { y =>
                y.toOption
              }

              loop(names.drop(2), curV)
            } else {
              val curV = vOp.flatMap { v =>
                v.get(x)
              }.map { x =>
                x.asInstanceOf[js.Dictionary[ErrorField]]
              }
              loop(xs, curV)
            }
          case Nil=>
            vOp.isDefined
        }
      }


      loop(names, Some(v))
    }


  }

}
